package com.neuedu.controller;

import com.neuedu.entity.UploadFile;
import com.neuedu.service.UploadFileService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "FileUploadServlet", value = "/up")
public class FileUploadServlet extends HttpServlet {


    UploadFileService service = new UploadFileService();


    public static final String UPLOAD_DIR = "D:\\upload\\";


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //判断是否支持  Multipart
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {

            DiskFileItemFactory factory = new DiskFileItemFactory();

            // Configure a repository (to ensure a secure temp location is used)
            //设置 Tomcat 接收到 文件 存放到那个临时目录
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            //解析 Request的流

            try {
                List<FileItem> fileItems = upload.parseRequest(request);
                for (FileItem fileItem : fileItems) {
                    String name = fileItem.getName();// package.png
                    String fieldName = fileItem.getFieldName();  //abc
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    String ext = name.substring(name.lastIndexOf("."));

                    String newFileName = uuid + ext;
                    File dist = new File(UPLOAD_DIR + newFileName);


                    fileItem.write(dist);//讲文件 从临时目录 转出到   D;\\upload
                    UploadFile uploadFile = new UploadFile();
                    uploadFile.setIp(getRemote(request));
                    uploadFile.setOriginName(name);
                    uploadFile.setPath(newFileName);
                    uploadFile.setSize(fileItem.getSize());
                    service.save(uploadFile);
                }
            } catch (FileUploadException e) {
                throw new RuntimeException(e);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

        response.sendRedirect(request.getContextPath()+"/filelist");


    }


    public String getRemote(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }

        return ipAddress;
    }


}
